<?php
/**
 * User: yunfengvico@163.com
 * Date: 2018/11/2 17:02
 * Desc:
 */
namespace App\Models;

class MemberScore extends BaseModel
{
    protected $table = 'member_score';

    public function getScoreList($where)
    {
        $rows = $this->_getPageList($where);
        return $rows;
    }

    /**
     * 变更用户积分信息
     * @param $mid int 用户ID
     * @param $score int 积分数
     * @param $type int 变更类型 1,增加;2,减少
     * @param $desc string 变更描述
     * @return bool
     */
    public function changeMemberScore($mid, $score, $type, $desc)
    {
        $memberModel = new Member();
        $memberInfo = $memberModel->_getOneById($mid);
        if(!$memberInfo) {
            $this->error = '用户不存在';
            return false;
        }
        $memberScore = $this->_getOne(['mid'=>$mid]);
        $memberModel->_start();
        try{
            if(!$memberScore) {
                $scoreData = [
                    'mid' => $mid,
                    'shop_id' => $memberInfo['shop_id'],
                    'admin_id' => $memberInfo['admin_id'],
                    'score' => $score,
                ];
                $this->_save($scoreData);
            } else {
                if($type == 1) {
                    $this->_inc(['mid' => $mid],'score', $score);
                } else {
                    if($score > $memberInfo['score']) {
                        $this->error = '兑换积分不得大于用户现有积分';
                        return false;
                    }
                    $this->_dec(['mid' => $mid],'score',$score);
                }
            }

            $scoreLogData = [
                'mid' => $mid,
                'shop_id' => $memberInfo['shop_id'],
                'admin_id' => $memberInfo['admin_id'],
                'score' => $score,
                'type' => $type,
                'desc' => $desc
            ];
            (new MemberScoreLog())->_save($scoreLogData);
            $memberModel->_commit();
            return true;
        }catch(\Exception $e) {
            $memberModel->_rollBack();
            $this->error = '用户积分信息处理失败';
            return false;
        }

    }
}